﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace LeafHttp.TestConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpClient httpClient = new HttpClient();
            httpClient.BaseUrl = "http://localhost:8000"; // 设置基础Url
            // 增加拦截器
            var interceptor = new RequestInterceptor();
            httpClient.AddInterceptor(interceptor);
            // 同步方式执行Post请求
            var rst = httpClient.Request(
                new RequestConfig()
                {
                    Url = "/Test/UpdateName",
                    Method = HttpMethod.Post,
                    Data = new Dictionary<string, object>
                    {
                        { "name", "命名1" }
                    }
                })
                .Execute();
            if (rst.IsSuccess)
            {
                Console.WriteLine("同步方式Post请求成功，返回数据为：" + rst.Response.Data);
            }
            else
            {
                Console.WriteLine("同步方式Post请求出错，错误信息为：" + rst.Message + (rst.Response != null ? " " + rst.Response.Data : string.Empty));
            }
            // 同步方式执行Get请求
            rst = httpClient.Request(
                new RequestConfig()
                {
                    Url = "/Test/GetName"
                })
                .Execute();
            if (rst.IsSuccess)
            {
                Console.WriteLine("同步方式Get请求成功，返回数据为：" + rst.Response.Data);
            }
            else
            {
                Console.WriteLine("同步方式Get请求出错，错误信息为：" + rst.Message + (rst.Response != null ? " " + rst.Response.Data : string.Empty));
            }
            // 异步方式执行请求
            httpClient.Request(
                new RequestConfig()
                {
                    Url = "/Test/UpdateName",
                    Method = HttpMethod.Post,
                    Data = new Dictionary<string, object>
                    {
                        { "name", "命名2" }
                    }
                })
                .ExecuteAsync((res) =>
                {
                    Console.WriteLine("异步方式请求成功，返回数据为：" + res.Data);
                },
                (err) =>
                {
                    Console.WriteLine("异步方式请求出错，错误信息为：" + err.Message + (err.Response != null ? " " + err.Response.Data : string.Empty));
                });
            // 异步方式执行Get请求
            httpClient.Get("/Test/GetName")
                .ExecuteAsync((res) =>
                {
                    Console.WriteLine("使用别名Get成功，返回数据为：" + res.Data);
                }, (err) =>
                {
                    Console.WriteLine("使用别名Get出错，错误信息为：" + err.Message + (err.Response != null ? " " + err.Response.Data : string.Empty));
                });
            // 异步方式执行Post请求
            httpClient.Post("/Test/UpdateName",
                new Dictionary<string, object>
                {
                    { "name", "LeafHttp" }
                })
                .ExecuteAsync((res) =>
                {
                    Console.WriteLine("使用别名Post成功，返回数据为：" + res.Data);
                }, (err) =>
                {
                    Console.WriteLine("使用别名Post出错，错误信息为：" + err.Message + (err.Response != null ? " " + err.Response.Data : string.Empty));
                });
            // 上传文件
            var uploadFileName = "upload.jpg";
            var uploadFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, uploadFileName);
            httpClient.Post("/Test/UploadFile",
                new Dictionary<string, object>
                {
                    { "file", new FormFile()
                        {
                            FileName = uploadFileName,
                            FileData = File.ReadAllBytes(uploadFilePath)
                        }
                    }
                },
                new RequestConfig()
                {
                    UseMultipartFormDataPost = true // 请求头的Content-Type自动设置为multipart/form-data
                })
                .ExecuteAsync((res) =>
                {
                    Console.WriteLine("上传文件成功，返回数据为：" + res.Data);
                }, (err) =>
                {
                    Console.WriteLine("上传文件出错，错误信息为：" + err.Message + (err.Response != null ? " " + err.Response.Data : string.Empty));
                });
            // 下载文件
            var saveFileName = "download.jpg";
            var saveFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, saveFileName);
            httpClient.Get("/Test/DownloadFile",
                new RequestConfig()
                {
                    ResponseDataType = ResponseDataType.ArrayBuffer
                })
                .ExecuteAsync((res) =>
                {
                    File.WriteAllBytes(saveFilePath, res.Data as byte[]);
                    Console.WriteLine("下载文件成功，文件保存至：" + saveFilePath);
                }, (err) =>
                {
                    Console.WriteLine("下载文件出错，错误信息为：" + err.Message + (err.Response != null ? " " + err.Response.Data : string.Empty));
                });
            Console.WriteLine("发起请求");
            Console.ReadLine();
        }
    }

    // 拦截器
    public class RequestInterceptor : IRequestInterceptor
    {
        public void Request(RequestConfig config)
        {
            Console.WriteLine("记录请求执行，Url地址：" + config.Url);
        }

        public void RequestError(Exception ex)
        {
            Console.WriteLine("记录请求出错，错误信息：" + ex.Message);
        }

        public void Response(ResponseResult response)
        {
            Console.WriteLine("记录收到回复，状态码为：" + response.Status);
        }

        public void ResponseError(ErrorResult error)
        {
            Console.WriteLine("记录回复出错，状态码为：" + (error.Response != null ? error.Response.Status.ToString() : "无"));
        }
    }
}
